/*
 * MultipleDocumentAction.java
 *
 * Created on March 27, 2005, 1:12 AM
 */

package tools;

import java.util.HashSet;
import java.util.Iterator;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

/**
 *
 * @author Keith
 */
abstract public class MultipleDocumentAction extends AbstractAction {
  
	private DocumentListener listener;
	private HashSet<Document> docs;

  public MultipleDocumentAction( String name, Icon icon ) {
		super( name, icon );

		listener = new DocumentListener() {
			public void changedUpdate( DocumentEvent evt ){
				docEvent( evt.getDocument() );
			}
			public void removeUpdate( DocumentEvent evt ){
				docEvent( evt.getDocument() );
			}
			public void insertUpdate( DocumentEvent evt ){
				docEvent( evt.getDocument() );
			}
		};

		docs = new HashSet<Document>();
	}

  public MultipleDocumentAction( String name ) {
		this( name, null );
  }

  public MultipleDocumentAction( Icon icon ) {
		this( null, icon );
  }

	private void docEvent(){
		boolean allPresent = true;
		Iterator<Document> iter = docs.iterator();

		while ( allPresent && iter.hasNext() ){
			allPresent = ( iter.next() ).getLength() > 0;
		}

		if ( allPresent != isEnabled() ){
			setEnabled( allPresent );
		}
	}

	private void docEvent( Document d ){
		if ( isEnabled() ){
			if ( d.getLength() == 0 ){
				setEnabled( false );
			}
		} else {
			docEvent();
		}
	}

	public void addDocument( Document doc ){
		if ( ! docs.contains( doc ) ){
			docs.add( doc );
			doc.addDocumentListener( listener );
			docEvent( doc );
		}
	}

	public void removeDocument( Document doc ){
		if ( docs.contains( doc ) ){
			doc.removeDocumentListener( listener );
			docs.remove( doc );
			docEvent();
		}
	}
}
